package test.serverframe.armc.server.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;

/**
 * @author LeiZhenYang
 * @date 2018.12.20
 */
public class FileUtil {
    public static void main(String[] args) throws IOException {
        File file = new File("F:\\Test\\Test.m2ts");
        long start = System.currentTimeMillis();
        Files.copy(file.toPath(), new File("D:\\UU\\temp.m2ts").toPath());
        System.out.println(System.currentTimeMillis() - start);
    }
    
    /**
     * 不能使用getClassLoader().getResource("...")方式读取resource文件，
     * 因为在打成jar包后，是以流的方式读取文件资源。
     * @author yegui  
     * @date 2019年2月22日  
     * @param path
     * @return
     * String
     */
    public static String readResource(String path) {
    	StringBuffer json = new StringBuffer();
    	InputStream is = FileUtil.class.getClassLoader().getResourceAsStream(path);
    	try {
			BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
			String line;
			while((line = br.readLine()) != null) {
				json.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return json.toString();
    }
    
    public static void loadJar(String jarPath, int value) throws Exception {
    	URL url = FileUtil.class.getClassLoader().getResource(jarPath);
    	File file = new File(url.getFile());
    	
    	File[] listFiles = file.listFiles(new FileFilter() {
			
			@Override
			public boolean accept(File file) {
				String fileName = file.getName();
				if (fileName.endsWith(".jar")) {
					return true;
				}
				return false;
			}
		});
    	URL[] urls = new URL[]{};
    	MyClassLoader myClassLoader = new MyClassLoader(urls);
    	myClassLoader.addJar(new File(jarPath).toURI().toURL());
    	Class<?> clazz = myClassLoader.loadClass("com.microcore.service.UserService");
    	Method method = clazz.getMethod("getUser", Integer.class);
    	//获取method参数集合
    	Class<?>[] paramTypes = method.getParameterTypes();
    	//创建反射方法要执行的参数
    	Object[] paramValues = new Object[paramTypes.length];
    	for (int i = 0; i < paramTypes.length; i++) {
    		String param = paramTypes[i].getSimpleName();
    		if (param.equals("Interger")) {
    			paramValues[i] = value;
    		} else if (param.equals("String")) {
    			paramValues[i] = null;
    		}
    	}
    	method.invoke(clazz.newInstance(), paramValues);
    	
    	myClassLoader.close();
    }
    
    static class MyClassLoader extends URLClassLoader {

        public MyClassLoader(URL[] urls) {
            super(urls);
        }

        public MyClassLoader(URL[] urls, ClassLoader parent) {
            super(urls, parent);
        }

        public void addJar(URL url) {
            this.addURL(url);
        }

    }
}
